<template>
  <el-card class="activity-list" style="margin: 20px;">
    <el-table :data="activities" border style="width: 100%">
      <el-table-column prop="title" label="活动名称"></el-table-column>
      <el-table-column prop="description" label="内容"></el-table-column>
      <el-table-column prop="startTime" label="开始时间"></el-table-column>
      <el-table-column prop="endTime" label="结束时间"></el-table-column>
      <el-table-column prop="location" label="地点"></el-table-column>

      <!-- 状态列 -->
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-tag :type="statusType(row.status)" size="small">
            {{ formatStatus(row.status) }}
          </el-tag>
          <!-- 结束按钮（仅限“未开始”状态） -->
          <el-button
            v-if="row.status === 0"
            @click="endActivity(row)"
            size="small"
            style="margin-left: 10px;"
          >
            结束
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
      style="margin-top: 20px"
    />
  </el-card>

  <!-- 发布新活动表单 -->
  <el-card class="publish-activity" style="margin: 20px;">
    <h3>发布新活动</h3>
    <el-form :model="newActivity" label-width="100px">
      <el-form-item label="标题">
        <el-input v-model="newActivity.title" placeholder="请输入活动名称" />
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker v-model="newActivity.startTime" type="datetime" placeholder="选择开始时间" value-format="YYYY-MM-DDTHH:mm:ss"/>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker v-model="newActivity.endTime" type="datetime" placeholder="选择结束时间" value-format="YYYY-MM-DDTHH:mm:ss"/>
      </el-form-item>
      <el-form-item label="地点">
        <el-input v-model="newActivity.location" placeholder="请输入活动地点" />
      </el-form-item>
      <el-form-item label="人数限制">
        <el-input-number v-model="newActivity.capacity" :min="1" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input type="textarea" v-model="newActivity.description" placeholder="非必填项" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlePublishActivity">发布活动</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
// 导入 getActivityList 接口
import { getActivityList, publishActivity } from '@/api/activity'

// 数据定义
const activities = ref([])
const total = ref(0)
const pageSize = ref(5)
const currentPage = ref(1)

// 新增活动表单数据
const newActivity = ref({
  title: '',
  startTime: '',
  endTime: '',
  location: '',
  capacity: 1,
  description: ''
})

// 获取活动数据
const fetchActivities = async () => {
  try {
    // 使用 getActivityList 接口获取活动列表
    const response = await getActivityList({
      page: Math.ceil(currentPage.value/10),
      size: pageSize.value*10
    });

    const rawData = Array.isArray(response.data) ? response.data : []

    // 分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    const paginatedData = rawData.slice(start, end)


    activities.value = paginatedData
    total.value = rawData.length
  } catch (error) {
    console.error('获取活动数据失败:', error)
    activities.value = []
    total.value = 0
    if(error.code == "ERR_NETWORK") {
      ElMessage.error('获取活动数据失败，请检查网络或稍后再试');
    } else if(error.response.status === 403) {
      ElMessage.error('无权限访问此页面，请重新登录');
    }
  }
}

// 状态标签类型映射
const statusType = (status) => {
  switch (status) {
    case '0':
    case '未开始':
      return 'info'
    case '1':
    case '进行中':
      return 'warning'
    case '2':
    case '已结束':
      return 'success'
    default:
      return 'info' // 默认返回 'info' 以避免无效的 prop
  }
}

// 将数字状态转换为中文文本
const formatStatus = (status) => {
  const statusMap = { '0': '未开始', '1': '进行中', '2': '已结束' }
  return statusMap[status] || status
}

// 分页切换
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchActivities()
}

// 结束活动
const endActivity = (row) => {
  row.status = '已结束'
}

// 发布活动
const handlePublishActivity = async () => {
  console.log('当前表单值:', newActivity.value) // 用于调试
  const now = new Date()

  // 设置时间为当天 00:00:00，用于判断是否是“今天或之后”
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const selectedStartTime = new Date(newActivity.value.startTime)
  const selectedEndTime = new Date(newActivity.value.endTime)

  // 验证开始时间是否早于今天
  if (selectedStartTime < todayStart) {
    ElMessage.error('开始时间不能早于今天')
    return
  }

  // 验证结束时间是否早于开始时间
  if (selectedEndTime < selectedStartTime) {
    ElMessage.error('结束时间不能早于开始时间')
    return
  }

  // 检查必填字段是否为空
  if (!newActivity.value.title || !newActivity.value.startTime || !newActivity.value.endTime || !newActivity.value.location || !newActivity.value.capacity) {
    ElMessage.error('请填写所有必填字段')
    return
  }

  try {
    // 调用后端接口发布活动
    const response = await publishActivity(newActivity.value);
    ElMessage.success('发布成功');

    // 将新活动加入列表
    const activity = {
      id: Date.now(),
      ...newActivity.value,
      status: '未开始',
    };
    activities.value.push(activity);

    // 重置表单
    newActivity.value = {
      title: '',
      startTime: '',
      endTime: '',
      location: '',
      capacity: 1,
      description: ''
    };

    // 可选：重新获取最新活动列表（根据后端返回）
    fetchActivities();
  } catch (error) {
    ElMessage.error('发布失败，请检查网络或输入内容');
    console.error('发布活动失败:', error);
  }
}

onMounted(() => {
  fetchActivities()
})
</script>

<style scoped>
.activity-list {
  margin: 20px;
}

.publish-activity {
  margin: 20px;
  text-align: left;
}
</style>